package com.tiyende.credit.loop.ui.activity

import android.graphics.Color
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.lib.common.permission.CommonPermissions
import com.lib.common.permission.OnPermissionCallback
import com.lib.common.permission.Permission
import com.tiyende.credit.loop.R
import com.tiyende.credit.loop.common.CommonActivity
import com.tiyende.credit.loop.databinding.TiyendeActivityPermissionListBinding
import com.tiyende.credit.loop.event.TiyendeEventPointType
import com.tiyende.credit.loop.ui.adapter.TiyendePermissionListAdapter
import com.tiyende.credit.loop.ui.contract.IViewContract
import com.tiyende.credit.loop.ui.presenter.TiyendePermissionListPresenter
import com.tiyende.credit.loop.utils.TiyendeDensityUtil
import com.tiyende.credit.loop.utils.decoration.LinearSpacingItemDecoration
import com.tiyende.credit.loop.utils.helper.TiyendeCreditStatusHelper
import com.tiyende.credit.loop.utils.helper.TiyendeProcessHelper
import com.tiyende.credit.loop.utils.shared.TiyendeSharedHelper
import com.tiyende.credit.loop.utils.shared.TiyendeSharedKey
import org.json.JSONObject

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/28 14:04
 * @Annotation：权限什么列表
 */
class TiyendePermissionListActivity: CommonActivity(), IViewContract.ITiyendePermissionListView {
    lateinit var binding: TiyendeActivityPermissionListBinding
    var presenter: TiyendePermissionListPresenter? = null

    private var listAdapter: TiyendePermissionListAdapter? = null

    override fun getTiyendeRootView(): View {
        binding = TiyendeActivityPermissionListBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initTiyendeView() {
        setTiyendeTitleBarVisibility(View.VISIBLE)
        setTiyendeBackBtnRes(R.mipmap.tiyende_back_white)
        setTiyendeRightBtnRes(R.mipmap.tiyende_customer_white)
        setTiyendeTextTitle(getString(R.string.tiyende_permission_list_title))
        setTiyendeTextTitleColor(Color.parseColor("#FFFFFFFF"))
        initTiyendePermissionListView()
    }

    override fun initTiyendeListener() {
        //联系客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("Permission List Page")
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_CUSTOMER,"Permission List Page")
        }

        binding.checkBoxPermission.setOnCheckedChangeListener { _, isChecked ->
            when (isChecked) {
                true -> {
                    binding.btAgree.isEnabled = true
                }
                false -> {
                    binding.btAgree.isEnabled = false
                }
            }
        }

        //拒绝
        binding.btDeny.setOnClickListener {
            TiyendeSharedHelper.addTiyendeSharedData(TiyendeSharedKey.TIYENDE_PERMISSION_PAGE_STATUS,-1)
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_PERMISSION_DENY,"Permission Page")

            val intent = intent
            intent.putExtra("isPermissionAgree",false)
            setResult(RESULT_OK,intent)
            finish()
        }

        //同意权限
        binding.btAgree.setOnClickListener {
            TiyendeSharedHelper.addTiyendeSharedData(TiyendeSharedKey.TIYENDE_PERMISSION_PAGE_STATUS,1)
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_PERMISSION_AGREE,"Permission Page")
            requestTiyendePermissionAction()
        }
    }

    override fun loadTiyendeData() {
        if (presenter == null){
            presenter = TiyendePermissionListPresenter(this)
        }
        presenter?.onTiyendeLoadPermissionList()
    }

    private fun initTiyendePermissionListView() {
        binding.recyclerViewPermission.layoutManager = LinearLayoutManager(this)
        listAdapter = TiyendePermissionListAdapter(binding.recyclerViewPermission)
        binding.recyclerViewPermission.adapter = listAdapter
        val leftDecoration = TiyendeDensityUtil.dp2px(10f)
        binding.recyclerViewPermission.addItemDecoration(LinearSpacingItemDecoration(0, 0,leftDecoration,leftDecoration))
        binding.recyclerViewPermission.itemAnimator = DefaultItemAnimator()
    }

    /**
     * 设置权限列表
     */
    override fun showTiyendePermissionList(pList: ArrayList<JSONObject>?) {
        listAdapter?.data = pList
    }

    /**
     * 权限申请成功
     */
    private fun showTiyendePermissionSuccess(){
        //进件信息未完成 - 进件信息页面
        if (TiyendeProcessHelper.queryTiyendeAuthenticationStepList().size > 0){
            onIntent(TiyendeAuthenticationStepsActivity::class.java)
            finish()
            return
        }

        val creditStatus = TiyendeProcessHelper.queryTiyendeAuthenticationBeforeRiskStatus()
        val isCreditRejected = TiyendeCreditStatusHelper.TiyendeCreditStatusRepository().isCreditRejected(creditStatus)
        //授信被拒绝 - 拒绝页面
        if (isCreditRejected){
            onIntent(TiyendeLimitRejectedActivity::class.java)
            finish()
            return
        }

        val isCreditReviewing = TiyendeCreditStatusHelper.TiyendeCreditStatusRepository().isCreditReviewing()
        //进件信息已完成 && 授信中 - 授信状态查询页面
        if (isCreditReviewing){
            onIntent(TiyendeLimitReviewingActivity::class.java)
            finish()
            return
        }
        //进件信息已完成 && 授信已完成 - 申贷试算页面
        TiyendeLoanApplyActivity.start(this)
        finish()
    }

    /**
     * 申请权限
     */
    private fun requestTiyendePermissionAction(){
        CommonPermissions.with(this)
            .permission(Permission.READ_SMS)
            .request(object: OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, p1: Boolean) {
                    if (p1){
                        var permissionString = ""
                        permissions.forEach {
                            permissionString = "$permissionString$it,"
                        }
                        addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_PERMISSION_SYSTEM_AGREE,permissionString.substring(0,permissionString.length - 1))

                        val intent = intent
                        intent.putExtra("isPermissionAgree",true)
                        setResult(RESULT_OK,intent)
                        finish()
                    }
                }
                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    var permissionString = ""
                    permissions.forEach {
                        permissionString = "$permissionString$it,"
                    }
                    addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_PERMISSION_SYSTEM_DENY,permissionString.substring(0,permissionString.length - 1))
                    CommonPermissions.startPermissionActivity(this@TiyendePermissionListActivity,Permission.READ_SMS)
                }
            })
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_PERMISSION_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_PERMISSION_END)
    }
}